package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;





import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiNewFindOrder;
import cn.com.api.entity.ApiT_order;
import cn.com.api.entity.ApiT_order_detail;
import cn.com.api.entity.ApiT_user_cash_records;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiU_coupon;
import cn.com.api.entity.ApiU_coupon_detail;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_order_detailMapper;
import cn.com.api.mapper.ApiT_user_cash_recordsMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_couponMapper;
import cn.com.api.mapper.ApiU_coupon_detailMapper;
import cn.com.api.service.ApiU_couponService;
import cn.com.api.service.impl.base.U_couponServiceImplBase;
import cn.com.util.Util;
import cn.com.util.Utils;


/**
 * 
 **/
@Service
public class ApiU_couponServiceImpl extends U_couponServiceImplBase implements ApiU_couponService{
	
	@Autowired
	private ApiU_couponMapper apiU_couponMapper;
	
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;
	
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	
	@Autowired
	private ApiU_coupon_detailMapper apiU_coupon_detailMapper;
	
	
	@Autowired
	private ApiT_user_cash_recordsMapper apiT_user_cash_recordsMapper;
	
	
	@Autowired
	private ApiT_order_detailMapper apiT_order_detailMapper;
    
	//日志工具
	private static Logger logger = Logger.getLogger(ApiU_couponServiceImpl.class);
		
     	//新增对象后返回记录ID
    public int U_couponInsertion(ApiU_coupon u_coupon){
        return this.apiU_couponMapper.U_couponInsertion(u_coupon);
    }
    
    
    public long queryUserMoney(String u_id) {
		ApiTmember member = apiTmemberMapper.findMemberByCuserid(u_id);
		if(member == null){
			return 0;
		}
		return member.getCmoney().longValue();
	}


	public void updUserMoney(String u_id, long resMoney) {
		ApiTmember member = new ApiTmember();
		member.setCmoney(Util.getBigDecimal(resMoney+""));
		apiTmemberMapper.updateApiTmember(member);
	}
    
    
	@Override
	public List<ApiU_coupon> findU_couponsByCondition(Map<String, Object> param) throws Exception {
		List<ApiU_coupon> list = this.apiU_couponMapper.findU_couponsByCondition(param);
		Date curDate = new Date();	
		
		for (ApiU_coupon apiU_coupon : list) {
			param.put("coupon_id", apiU_coupon.getCoupon_id());
			int sum = apiU_coupon_detailMapper.findU_coupon_details_NumByCondition(param);
			//处理增加过期状态，当天为即将过期（无明确需求，人为定义）
			long amount = apiU_coupon.getCoupon_count();
			int flag = 0;
			Date endDate = parseDay(apiU_coupon.getEnd_time());
			if(endDate == null){
				flag = -1;
			}else{			
				flag = endDate.compareTo(curDate);  
			}
			if(flag < 0){
				//已经过期。
				apiU_coupon.setExt2("0");
			}else if(flag == 0){
				//即将过期
				apiU_coupon.setExt2("1");		
			}else{
				//进行中
				apiU_coupon.setExt2("2");
			}		
			apiU_coupon.setExt1(""+(amount - sum));			
		}				
		return list;
	}
	
	/**
	 * 转换日期格式（暂时写在这里，后续转移至公共util类中）
	 * @param num
	 * @param newDate
	 * @return
	 * @throws ParseException
	 */
	public static Date parseDay(String newDate) throws ParseException{
		try {
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date  currdate = format.parse(newDate);
			return currdate;
		} catch (Exception e) {
			logger.error("==========[ApiU_couponServiceImpl[处理日期出错newDate:["+newDate+"]]]=========",e);
			return null;
		}
	}



	@Override
	public int updateU_coupon_info(ApiU_coupon u_coupon) {
		int ret_I= apiU_couponMapper.updateU_coupon_info(u_coupon);
		return ret_I;
	}


	
	@Override
	public void insertU_coupon_info(ApiU_coupon u_coupon) {
		
		apiU_couponMapper.insertU_coupon_info(u_coupon);
		
		
	}



	@Transactional
	@Override
	public List<Object> insertU_coupon_info(ApiU_coupon u_coupon,
			List<Map<String, Object>> list)  throws Exception{
		List<Object> listresult = new ArrayList<Object>();
		if(list == null || list.size()== 0){
			u_coupon.setCoupon_amout(0);
			u_coupon.setUse_limit1("");
			u_coupon.setCoupon_count(Long.parseLong("0"));
			u_coupon.setEnd_time("");
			apiU_couponMapper.insertU_coupon_info(u_coupon);
			listresult.add(u_coupon.getCoupon_id());
		}else{		
			for (Map<String, Object> map : list) {				
				int coupon_amout = (Integer)map.get("coupon_amout");
				String use_limit1 = map.get("use_limit1").toString();
				long coupon_count = (Long)map.get("coupon_count");
				String end_time = map.get("end_time").toString();
				String begin_time = map.get("start_time").toString();
				String deposit_amount =  map.get("deposit_amount").toString();
				u_coupon.setDeposit_amount(Integer.parseInt(deposit_amount));
				u_coupon.setCoupon_amout(coupon_amout);
				u_coupon.setUse_limit1(use_limit1);
				u_coupon.setCoupon_count(coupon_count);
				u_coupon.setEnd_time(end_time);
				u_coupon.setStart_time(begin_time);	
				apiU_couponMapper.insertU_coupon_info(u_coupon);
				listresult.add(u_coupon.getCoupon_id());
			}
		}
		
		return listresult;
	}


	@Transactional
	@Override
	public void updateU_coupon_info(ApiU_coupon u_coupon,
			List<Map<String, Object>> list, String[] coupon_id_list) throws Exception{
		//删除原先的
		if(coupon_id_list != null && coupon_id_list.length != 0){
			for (String str : coupon_id_list) {
				apiU_couponMapper.deleteU_coupon(Integer.parseInt(str));
			}
		}
		
		if(list == null || list.size()== 0){
			u_coupon.setCoupon_amout(0);
			u_coupon.setUse_limit1("");
			u_coupon.setCoupon_count(Long.parseLong("0"));
			u_coupon.setEnd_time("");
			apiU_couponMapper.insertU_coupon_info(u_coupon);
		}else{		
			for (Map<String, Object> map : list) {				
				int coupon_amout = (Integer)map.get("coupon_amout");
				String use_limit1 = (String)map.get("use_limit1");
				long coupon_count = (Long)map.get("coupon_count");
				String end_time = (String)map.get("end_time");				
				u_coupon.setCoupon_amout(coupon_amout);
				u_coupon.setUse_limit1(use_limit1);
				u_coupon.setCoupon_count(coupon_count);
				u_coupon.setEnd_time(end_time);				
				apiU_couponMapper.insertU_coupon_info(u_coupon);
			}
		}	
		
		
	}



	@Override
	public List<ApiU_coupon> findU_couponsByUserid(Map<String, Object> params)
			throws Exception {
		
		return apiU_couponMapper.findU_couponsByUserid(params);
	}



	@Override
	public ApiU_coupon findU_couponsDetailByCouponid(
			Map<String, Object> params) throws Exception {
		
		return apiU_couponMapper.findU_couponsDetailByCouponid(params);
	}



	@Override
	public List<ApiU_coupon> findU_coupons_info(Map<String, Object> params)
			throws Exception {
		
		return apiU_couponMapper.findU_couponsByCondition(params);
	}


	@Transactional
	@Override
	public Map<String, Object> findU_coupons_buy(Map<String, Object> params) throws Exception {

		Map<String,Object> map = new HashMap<String,Object>();
		String pay_type = (String)params.get("pay_type");
		String user_id = (String)params.get("user_id");
		String coupon_id = (String)params.get("coupon_id");
		long sumMoney = (Long)params.get("buy_amount");
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if ((ApiNewFindOrder.PAY_TYPE_YY).equals(pay_type)) {
			// 查询账户总金额
			long cMoney = queryUserMoney(user_id);
			// 判断金额大小写，购买金额大于账户金额，返回错误消息，购买金额小于等于账户金额，交易成功

			if (sumMoney > cMoney) {
				map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
				map.put(Utils.MESSAGE, "余额不足！");
			} else {
				String order_no = Utils.getDingDanNo("");//订单号
				// 更新账户余额		
				long resMoney = cMoney - sumMoney;// 暂时的余额
				updUserMoney(user_id, resMoney);			
				//插入扣款流水账
				ApiT_user_cash_records t_user_cash_records = new ApiT_user_cash_records();
				t_user_cash_records.setCreate_time(sd.format(new Date()));
				t_user_cash_records.setMoney(BigDecimal.valueOf(sumMoney));				
				t_user_cash_records.setUser_id(user_id);
				t_user_cash_records.setCate_type(10);
				t_user_cash_records.setPay_type(0);
				t_user_cash_records.setPay_type_desc(0+"");
				t_user_cash_records.setProcess_type(1);
				t_user_cash_records.setOrder_id(order_no);
				t_user_cash_records.setRemark("优惠券购买");
				
				apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(t_user_cash_records);
				// 插入优惠券流水
				ApiU_coupon_detail u_coupon_detail = new ApiU_coupon_detail();
				u_coupon_detail.setBalance_price(0);
				u_coupon_detail.setBalance_time(new Date().getTime());
				u_coupon_detail.setCoupon_id(coupon_id);
				u_coupon_detail.setExt1("");
				u_coupon_detail.setExt2("");
				u_coupon_detail.setExt3("");
				u_coupon_detail.setExt4("");
				u_coupon_detail.setExt5("");
				u_coupon_detail.setIs_balance(0);//未结算
				u_coupon_detail.setOrder_no(order_no);
				u_coupon_detail.setStatus(1);//已支付
				u_coupon_detail.setUse_time(sd.format(new Date()));
				u_coupon_detail.setUser_id(user_id);
				apiU_coupon_detailMapper.insertU_coupon_detail(u_coupon_detail);
				
				
				
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "支付成功！");
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "目前只支持余额支付！");
		}
		return map;
		
		
	}


	@Override
	public void insertU_coupon_order(ApiT_order t_order) {
		apiT_orderMapper.insertT_order_info(t_order);
	}


	@Override
	public void insertU_coupon_order_detail(ApiT_order_detail apiT_order_detail) {
		
		//apiT_order_detailMapper.insertT_order_detail(apiT_order_detail);
		apiT_order_detailMapper.insertT_order_detail_info(apiT_order_detail);
		
	}

	@Transactional
	@Override
	public void upd_coupons_status(String coupon_id_list) throws Exception {
		String[] coupon_list = coupon_id_list.split(",");
		for (String coupon_id : coupon_list) {
			
			ApiU_coupon apiU_coupon = apiU_couponMapper.findU_couponById(Integer.valueOf(coupon_id));
			apiU_coupon.setDeposit_status(1);//支付状态
			apiU_couponMapper.updateU_coupon_info(apiU_coupon);
		}
		
		
	}


	@Override
	public List<Map<String,Object>> getOrdersList(Map<String, Object> param)
			throws Exception {
		
		
		return apiU_couponMapper.getOrdersList(param);
	}
 
}


